package threadbase;

import sun.security.util.SecurityConstants;

import java.io.BufferedReader;
import java.io.FilePermission;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.*;
import java.util.Collections;

/**
 * java 线程安全
 *
 * @author xujian
 * Creation date 2024/4/9 22:57
 * @version 1.0
 */
public class JavaThreadSecurityDemo2 {

    public static void main(String[] args) {
        final String filePath = "C:\\Users\\toptea\\Desktop\\新建文本文档.txt";

        // 假设这是从某个安全策略或配置中获取的权限集合
        Permission readPermission = new FilePermission(filePath, "read");
        PermissionCollection permissionCollection = new Permissions();
        permissionCollection.add(readPermission);

        ProtectionDomain domain = new ProtectionDomain(null, permissionCollection,JavaThreadSecurityDemo2.class.getClassLoader() , null);
        // 创建AccessControlContext，包含我们希望应用的权限
        AccessControlContext customACC = new AccessControlContext(new ProtectionDomain[]{domain});

        // 在指定的AccessControlContext中执行文件读取操作
        String content = AccessController.doPrivileged(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return readFile(filePath);
            }
        },customACC);

        System.out.println("File content: " + content);
    }

    private static String readFile(String filePath) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException("Error reading file", e);
        }
    }
}


